package server.core;

import server.*;
import server.connector.http.HttpRequestImpl;
import server.connector.http.HttpResponseImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SimpleContextValve implements Valve, Contained {
    protected Container container;
    @Override
    public Container getContainer() {
        return container;
    }

    @Override
    public void setContainer(Container container) {
        this.container = container;
    }

    @Override
    public String getInfo() {
        return null;
    }

    @Override
    public void invoke(HttpRequestImpl request, HttpResponseImpl response, ValveContext valveContext) throws IOException, ServletException {
        SimpleContext context = (SimpleContext)getContainer();
        String requestURI = request.getDecodedRequestURI();
        SimpleWrapper wrapper = null;
        try {
            wrapper = (SimpleWrapper)context.map(request, true);
        } catch (IllegalArgumentException e) {
            badRequest(requestURI, response);
            return;
        }
        if (wrapper == null) {
            notFound(requestURI, response);
            return;
        }
        wrapper.invoke(request, response);
    }

    private void badRequest(String requestURI, HttpServletResponse response) {
        try {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, requestURI);
        }
        catch (IllegalStateException e) {
            ;
        }
        catch (IOException e) {
            ;
        }
    }

    private void notFound(String requestURI, HttpServletResponse response) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, requestURI);
        }
        catch (IllegalStateException e) {
            ;
        }
        catch (IOException e) {
            ;
        }
    }
}
